package com.behelpful.common.core.result;

import lombok.Data;
import lombok.ToString;

import java.io.Serializable;

/**
 * 统一返回数据体
 *
 * @author Alay
 * @date 2021-07-07 08:56
 */
@Data
@ToString
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 响应代码
     */
    private String code;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应结果
     */
    private T data;

    private static <T> R<T> restResult(T data, String code, String message) {
        return new R<>().data(data).code(code).message(message);
    }

    public static R result(BaseResult resultEnum) {
        return new R().code(resultEnum.getCode()).message(resultEnum.getMessage());
    }


    public static <T> R<T> ok() {
        return restResult(null, OkResult.SUCCESS.getCode(), OkResult.SUCCESS.getMessage());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, OkResult.SUCCESS.getCode(), OkResult.SUCCESS.getMessage());
    }

    public static <T> R<T> ok(T data, String message) {
        return restResult(data, OkResult.SUCCESS.getCode(), message);
    }


    public static <T> R<T> failed() {
        return result(FailedResult.FAILED);
    }

    public static <T> R<T> failed(String message) {
        return restResult(null, FailedResult.FAILED.getCode(), message);
    }

    public static <T> R<T> failed(String code, String message) {
        return restResult(null, code, message);
    }


    public static <T> R<T> error() {
        return result(ErrorResult.UN_KNOW_ERROR);
    }


    public static <T> R<T> exception(BaseResult errorResult) {
        return result(errorResult);
    }

    public R code(String code) {
        this.code = code;
        return this;
    }

    public R message(String message) {
        this.message = message;
        return this;
    }

    public R data(T data) {
        this.data = data;
        return this;
    }
}